<?php
/**
 * 落地数据
 * User: lyl
 * Date: 2019-04-29
 */

namespace Biz\module\Classes\WikiClean;

use Biz\model\wiki\WikiClean as mWikiClean;
use Doraemon\model\Store\ShenJianGoods as mShenJianGoods;
use Doraemon\model\Store\ShenJianGoodsSourceData as mShenJianGoodsSourceData;
use Doraemon\model\Store\ShenJianMap as mShenJianMap;
use Doraemon\tools\Log;

class Run
{
    const RUN_ACTION = [
        1 => 'goods',
        2 => 'sku',
        3 => 'attribute',
        4 => 'category',
        5 => 'brand',
        6 => 'images',
    ];

    private static $data = [];

    /**
     * 执行统一操作
     **/
    public static function run($params)
    {
        Log::debug('<============wiki清洗日志记录传值============>', func_get_args());

        if (isset($params['data']['id']) && !empty($params['data']['id'])) {
            $getParams = [];
            $getParams = mShenJianGoods::get('*', ['id' => $params['data']['id']]);

            if (!empty($getParams)) {
                $getParams['url'] = mShenJianMap::get('real_url', ['res_id' => $params['data']['id']]);
                $sourceData = mShenJianGoodsSourceData::get(
                    ['source_data', 'images', 'params',],
                    ['shenjian_goods_id' => $params['data']['id'], 'ORDER' => ['id' => 'DESC']]);
                $getParams = array_merge($getParams, $sourceData);

                foreach (self::RUN_ACTION as $_k => &$_v) {
                    $class = 'Biz\module\Classes\WikiClean\\' . ucfirst($_v);
                    $ref = new \ReflectionClass($class);
                    if ($ref->hasMethod('run')) {
                        call_user_func_array([$class, 'run'], [$getParams, &self::$data]);
                    }
                }

                self::_add(self::$data);
            }

        }

        return self::$data;
    }

    /**
     * 插入表
     **/
    private static function _add(&$data)
    {
        if (!empty($data)) {
            Log::debug('<============wiki清洗日志记录清洗的值============>', $data);

            $save = [
                'res_id' => $data['goods']['res_id'],
                'content' => json_encode($data, true),
                'add_time' => date('Y-m-d H:i:s'),
                'edit_time' => date('Y-m-d H:i:s'),
            ];
            //执行入库操作
            $insertAction = mWikiClean::insertData($save);

            //失败记录日志
            if (!$insertAction) {
                Log::debug('<============wiki清洗日志记录失败============>', $save);
            }
        }
    }

}